package com.openspring.platform.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.openspring.framework.service.AbstractGenericService;
import com.openspring.platform.dao.ResourceDAO;
import com.openspring.platform.model.Resource;
import com.openspring.platform.model.node.ResourceNode;
import com.openspring.platform.service.ResourceService;

@Service("resourceService")
public class ResourceServiceImpl extends AbstractGenericService<Resource, Long> implements ResourceService {
	
	private ResourceDAO resourceDAO;

	@javax.annotation.Resource(name = "resourceDAO")
	public void setResourceDAO(ResourceDAO resourceDAO) {
		this.resourceDAO = resourceDAO;
		super.setGenericDAO(resourceDAO);
	}

	@Override
	public ResourceNode getResourceTree() {
		ResourceNode root = new ResourceNode();
		root.setText(".");
		List<Resource> entities = resourceDAO.queryWhere(" WHERE status = ?", "enable");
		Map<Long, ResourceNode> map = new HashMap<Long, ResourceNode>();
		Iterator<Resource> iter = entities.iterator();
		while(iter.hasNext()) {
			ResourceNode node = new ResourceNode();
			Resource entity = iter.next();
			BeanUtils.copyProperties(entity, node);
			map.put(node.getId(), node);
		}
		Set<Map.Entry<Long, ResourceNode>> entrySet = map.entrySet();
		Iterator<Map.Entry<Long, ResourceNode>> iter1 = entrySet.iterator();
		while(iter1.hasNext()) {
			ResourceNode node = iter1.next().getValue();
			if(node.getParentId() == 0) {
				root.getChildren().add(node);
			} else {
				ResourceNode parentNode = map.get(node.getParentId());
				if(parentNode != null)
					parentNode.getChildren().add(node);
			}
		}
		root.sort(SortOrder.ASCENDING);
		return root;
	}

	@Override
	public List<Resource> findAllChildren(Long id) {
		return resourceDAO.queryAllChildren(id);
	}

	@Override
	public List<Resource> findChildren(Long id) {
		return resourceDAO.queryChildren(id);
	}

	@Override
	public List<Resource> findEnableChildren(Long id) {
		return resourceDAO.queryEnableChildren(id);
	}
}
